package com.jinbo.sxzq;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.v4.os.IResultReceiver;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/***************棋盘部署时的操作视图********************/
public class GameDeployView extends SurfaceView implements SurfaceHolder.Callback {
    GameActivity gameActivity;
    GameDeployViewDrawThread gameDeployViewDrawThread;//绘制线程的引用
    GameControl gameControl;//游戏控制器
    final int BoardWidthForOne = 80;//一格棋盘的大小
    Paint paint_1;//画笔
    Paint paint_2;
    Paint paint_3;
    TextPaint textPaint;
    int[][] chess_depliylocation;//保存棋子在部署阶段的位置信息
    int board_width = ProjectConstants.BoardAttributes.WIDTH;//棋盘宽度
    int board_length = ProjectConstants.BoardAttributes.LENGTH;//棋盘长度
    int max_deploy;//最大棋子可部署数
    int first_boardLocationX;//第一块棋盘的x坐标
    int first_boardLocationY;//第一块棋盘的y坐标

    //触摸相关参数
    boolean touch_flag = false;//是否选中了棋子
    int touch_type = 0;//选中棋子的类型
    int[] touch_what;//选中棋子的位置：部署区域的棋子横坐标为-1

    //棋子显示信息相关参数
    Bitmap[] chessBitmap;//棋子图片数组
    Bitmap background;//背景图片
    String[] chessMasage;//棋子的介绍信息

    public GameDeployView(GameActivity gameActivity){
        super(gameActivity);
        this.gameActivity = gameActivity;
        getHolder().addCallback(this);//实现Callback方法
        gameControl = gameActivity.gameControl;
        max_deploy = gameControl.max_deploy;
        init();//初始化图片方法
        this.gameDeployViewDrawThread = new GameDeployViewDrawThread(this);//实例化绘制线程
    }

    public void init(){
        paint_1 = new Paint();
        paint_1.setAntiAlias(true);//抗锯齿
        paint_1.setFilterBitmap(true);//滤波处理
        paint_2 = new Paint();
        paint_2.setAntiAlias(true);//抗锯齿
        paint_2.setFilterBitmap(true);//滤波处理
        paint_3 = new Paint();
        paint_3.setAntiAlias(true);//抗锯齿
        paint_3.setFilterBitmap(true);//滤波处理
        textPaint = new TextPaint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(40);
        chess_depliylocation = new int[3][max_deploy];
        for(int i = 0 ; i < max_deploy ; i++){//初始化部署区域棋子的位置信息
            chess_depliylocation[0][i] = 30+(i%4)*(BoardWidthForOne+50);
            chess_depliylocation[1][i] = 900+(i/4)*(BoardWidthForOne+50);
            chess_depliylocation[2][i] = ProjectConstants.ChessState.NO_DEPLOY;
        }
        first_boardLocationX = 30;
        first_boardLocationY = 30;

        //初始化介绍信息
        //background = BitmapFactory.decodeResource(getResources(),R.drawable.welcome_backgroud);
        //Matrix matrix = new Matrix();//对原有图片缩放
        //matrix.postScale((float) gameActivity.windowsizex/background.getWidth(),(float) gameActivity.windowsizey/background.getHeight());
        //background = Bitmap.createBitmap(background,0,0,background.getWidth(),background.getHeight(),matrix,true);
        //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.menu);
        //for(int i = 0 ; i < menuBitmap.length ; i++){//初始化四张子图
        // menuBitmap[i] = Bitmap.createBitmap(bitmap,0,i*(bitmap.getHeight()/menuBitmap.length),bitmap.getWidth(),(bitmap.getHeight()/menuBitmap.length));
        //}
        //bitmap = null;//释放图片资源
        chessMasage = new String[]{"",ProjectConstants.ChessMasage.SHU,ProjectConstants.ChessMasage.NUI,ProjectConstants.ChessMasage.HU,
                ProjectConstants.ChessMasage.TU,ProjectConstants.ChessMasage.LONG,ProjectConstants.ChessMasage.SHE,
                ProjectConstants.ChessMasage.MA,ProjectConstants.ChessMasage.YANG,ProjectConstants.ChessMasage.HOU,
                ProjectConstants.ChessMasage.JI,ProjectConstants.ChessMasage.GOU,ProjectConstants.ChessMasage.ZHU};

        chessBitmap = gameActivity.chess_bitmaps;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //绘制棋盘
        super.onDraw(canvas);
        paint_1.setColor(Color.WHITE);
        canvas.drawRect(25,25,(35+BoardWidthForOne*board_width),(35+BoardWidthForOne*board_width),paint_1);
        paint_1.setColor(Color.GRAY);
        paint_2.setColor(Color.BLACK);
        paint_3.setColor(Color.YELLOW);
        //绘制棋盘
        for(int i = 0 ; i < board_width ; i++){
            for(int j = 0 ; j < board_length ; j++){
                if((i+j)%2 == 0){
                    canvas.drawRect(first_boardLocationX+j*BoardWidthForOne,
                            first_boardLocationY+i*BoardWidthForOne,
                            first_boardLocationX+(j+1)*BoardWidthForOne,
                            first_boardLocationY+(i+1)*BoardWidthForOne,paint_1);
                }else{
                    canvas.drawRect(first_boardLocationX+j*BoardWidthForOne,
                            first_boardLocationY+i*BoardWidthForOne,
                            first_boardLocationX+(j+1)*BoardWidthForOne,
                            first_boardLocationY+(i+1)*BoardWidthForOne,paint_2);
                }
                if(gameControl.getBoardChess(i,j) > 0){
                    Rect srcRect = new Rect(0,0,
                            chessBitmap[gameControl.getBoardChess(i,j)-1].getWidth(),chessBitmap[gameControl.getBoardChess(i,j)-1].getHeight());
                    Rect destRect = new Rect(first_boardLocationX+j*BoardWidthForOne,
                            first_boardLocationY+i*BoardWidthForOne,
                            first_boardLocationX+(j+1)*BoardWidthForOne,
                            first_boardLocationY+(i+1)*BoardWidthForOne);
                    canvas.drawBitmap(chessBitmap[gameControl.getBoardChess(i,j)-1],srcRect,destRect,null);
                }
            }
        }
        //绘制棋子部署区域
        paint_2.setColor(Color.GRAY);
        paint_1.setColor(Color.WHITE);
        for(int i = 0 ; i < max_deploy ; i++){
            if(chess_depliylocation[2][i] == ProjectConstants.ChessState.NO_DEPLOY){
                canvas.drawRect(chess_depliylocation[0][i],
                        chess_depliylocation[1][i],
                        chess_depliylocation[0][i]+BoardWidthForOne,
                        chess_depliylocation[1][i]+BoardWidthForOne,paint_1);
            }else{
                canvas.drawRect(chess_depliylocation[0][i],
                        chess_depliylocation[1][i],
                        chess_depliylocation[0][i]+BoardWidthForOne,
                        chess_depliylocation[1][i]+BoardWidthForOne,paint_2);
            }
            Rect srcRect = new Rect(0,0,chessBitmap[0].getWidth(),chessBitmap[0].getHeight());
            Rect destRect = new Rect(chess_depliylocation[0][i]+5,
                    chess_depliylocation[1][i]+5,
                    chess_depliylocation[0][i]+BoardWidthForOne-5,
                    chess_depliylocation[1][i]+BoardWidthForOne-5);
            canvas.drawBitmap(chessBitmap[i],srcRect,destRect,null);
        }
        //绘制棋子详细介绍
        paint_1.setColor(Color.WHITE);
        paint_2.setColor(Color.YELLOW);
        canvas.drawRect(30,1300,900,1500,paint_1);
        canvas.drawRect(40,1320,140,1420,paint_2);
        StaticLayout staticLayout = new StaticLayout(chessMasage[touch_type],textPaint,700, Layout.Alignment.ALIGN_NORMAL,1.0F,0.0F,true);
        canvas.translate(160,1300);
        staticLayout.draw(canvas);
    }
/*
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        double x = event.getX();
        double y = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(x > chess_depliylocation[0][0] && x < chess_depliylocation[0][max_deploy-1] + BoardWidthForOne
                && y > chess_depliylocation[1][0] && x < chess_depliylocation[1][max_deploy-1] + BoardWidthForOne){//触摸部署区域（部署操作）
                    int[] touchwhat = TouchDeployWhere(x,y);
                    if(touchwhat[1] >= 0 && chess_depliylocation[2][touchwhat[1]] == ProjectConstants.ChessState.NO_DEPLOY){
                        touch_flag = true;
                        touch_type = touchwhat[1]+1;
                        toch_what = touchwhat;
                        touch_board = false;
                    }
                    Log.e("触摸事件","开始部署触摸事件");
                }
                if(x > first_boardLocationX && x < first_boardLocationX+ board_width*BoardWidthForOne
                && y > first_boardLocationY && y < first_boardLocationY + board_length*BoardWidthForOne){//触摸棋盘区域（调整操作）
                    int[] toch = TouchBoardWhere(x,y);
                    if(toch != null && gameControl.getBoardChess(toch[0],toch[1]) != ProjectConstants.ChessType.KONG
                            && gameControl.getBoardOwner(toch[0],toch[1]) != ProjectConstants.ChessOwner.ENEMY){
                        touch_flag = true;
                        touch_board = true;
                        toch_what = toch;
                        touch_type = gameControl.getBoardChess(toch[0],toch[1]);
                    }
                    Log.e("触摸事件","开始调整触摸事件");
                }
                return true;
            case MotionEvent.ACTION_UP:
                if(touch_flag && x > first_boardLocationX && x < first_boardLocationX+ board_width*BoardWidthForOne
                        && y > first_boardLocationY && y < first_boardLocationY + board_length*BoardWidthForOne){//触摸棋盘区域（调整操作）
                    int[] toch = TouchBoardWhere(x,y);
                    if(toch != null && gameControl.getBoardChess(toch[0],toch[1]) == 0 && toch[0] > board_length/2){
                        //向棋盘部署
                        gameControl.setBoard(toch[0],toch[1],touch_type);
                        gameControl.setBoardOwner(toch[0],toch[1],ProjectConstants.ChessOwner.OUR);
                        //移除原位置
                        if(touch_board == true){//是从棋盘移动
                            gameControl.setBoard(toch_what[0],toch_what[1],ProjectConstants.ChessType.KONG);
                            gameControl.setBoardOwner(toch_what[0],toch_what[1],ProjectConstants.ChessOwner.EMPTY);
                        }else{//是从部署区域移动
                            chess_depliylocation[2][toch_what[1]] = ProjectConstants.ChessState.DEATH;
                        }
                    }
                    Log.e("触摸事件","调整完成触摸事件");
                }else{//撤下操作
                    if(touch_board == true){//从棋盘撤下
                        chess_depliylocation[2][gameControl.getBoardChess(toch_what[0],toch_what[1])] = ProjectConstants.ChessState.NO_DEPLOY;
                        gameControl.setBoard(toch_what[0],toch_what[1],ProjectConstants.ChessType.KONG);
                    }
                    Log.e("触摸事件","撤下触摸事件");
                }
                touch_board = false;
                touch_flag = false;
                toch_what = null;
                touch_type = 0;
                break;
            default:
                Log.e("触摸事件","未知的触摸事件");
        }
        return super.onTouchEvent(event);
    }
 */

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        double x = event.getX();
        double y = event.getY();
        if(event.getAction() == MotionEvent.ACTION_DOWN){
            //触摸部署区域
            if(x > chess_depliylocation[0][0] && x < chess_depliylocation[0][max_deploy-1] + BoardWidthForOne
                    && y > chess_depliylocation[1][0] && x < chess_depliylocation[1][max_deploy-1] + BoardWidthForOne){
                int[] touch = TouchDeployWhere(x,y);
                    if(touch_flag == true){//已经选中了要操作的棋子
                        if(touch_what[0] != -1){//棋子在棋盘：撤下棋子
                            chess_depliylocation[2][gameControl.getBoardChess(touch_what[0],touch_what[1])-1] = ProjectConstants.ChessState.NO_DEPLOY;
                            gameControl.setBoard(touch_what[0],touch_what[1],ProjectConstants.ChessType.KONG);
                            gameControl.num_deploy--;
                            touch_what = null;
                            touch_flag = false;
                            touch_type = 0;
                        }else{//棋子在部署区域：重新选中
                            if(touch != null && chess_depliylocation[2][touch[1]] == ProjectConstants.ChessState.NO_DEPLOY){
                                touch_what = touch;
                                touch_type = touch_what[1]+1;
                                touch_flag = true;
                            }
                        }
                    }else{//未选中棋子
                        if(touch != null && chess_depliylocation[2][touch[1]] == ProjectConstants.ChessState.NO_DEPLOY){//选中棋子
                            touch_what = touch;
                            touch_type = touch_what[1]+1;
                            touch_flag = true;
                        }
                    }
                    return true;
            }
            //触摸棋盘区域
            if(x > first_boardLocationX && x < first_boardLocationX+ board_width*BoardWidthForOne
                    && y > first_boardLocationY && y < first_boardLocationY + board_length*BoardWidthForOne){
                int[] touch = TouchBoardWhere(x,y);
                if(touch_flag == true){//已经选中了棋子
                    if(touch != null && gameControl.getBoardChess(touch[0],touch[1]) == 0 && touch[0] >= board_length/2){//部署位置合法
                        gameControl.setBoard(touch[0],touch[1],touch_type);
                        gameControl.setBoardOwner(touch[0],touch[1],ProjectConstants.ChessOwner.OUR);
                        if(touch_what[0] == -1){
                            chess_depliylocation[2][touch_what[1]] = ProjectConstants.ChessState.DEPLOY;
                            gameControl.num_deploy++;
                        }else{
                            gameControl.setBoardOwner(touch_what[0],touch_what[1],ProjectConstants.ChessOwner.EMPTY);
                            gameControl.setBoard(touch_what[0],touch_what[1],ProjectConstants.ChessType.KONG);
                        }
                        touch_flag = false;
                        touch_type = 0;
                        touch_what = null;
                        return true;
                    }
                }else{
                    if(touch != null && gameControl.getBoardOwner(touch[0],touch[1]) == ProjectConstants.ChessOwner.OUR && gameControl.getBoardChess(touch[0],touch[1]) != 0){//选中合理
                        touch_what = touch;
                        touch_flag = true;
                        touch_type = gameControl.getBoardChess(touch[0],touch[1]);
                        return true;
                    }
                }
            }
            //触摸其他区域
            if(touch_flag == true && touch_what[0] != -1){
                chess_depliylocation[2][gameControl.getBoardChess(touch_what[0],touch_what[1])-1] = ProjectConstants.ChessState.NO_DEPLOY;
                gameControl.num_deploy--;
                gameControl.setBoardOwner(touch_what[0],touch_what[1],ProjectConstants.ChessOwner.EMPTY);
                gameControl.setBoard(touch_what[0],touch_what[1],ProjectConstants.ChessType.KONG);
                touch_flag = false;
                touch_type = 0;
                touch_what = null;
            }
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        gameDeployViewDrawThread.setFlag(true);
        gameDeployViewDrawThread.start();//开启绘制线程
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        gameDeployViewDrawThread.setFlag(false);//关闭绘制线程
        while (retry) {
            try {
                gameDeployViewDrawThread.join();//阻塞线程
                retry = false;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public int[] TouchDeployWhere(double TouchX , double TouchY){//将触摸坐标位置转换为部署区域位置
        for(int i = 0 ; i < max_deploy ; i++){
            if(TouchX>chess_depliylocation[0][i] && TouchX<chess_depliylocation[0][i]+BoardWidthForOne
            && TouchY>chess_depliylocation[1][i] && TouchY<chess_depliylocation[1][i]+BoardWidthForOne){
                return new int[]{-1,i};
            }
        }
        return null;
    }

    public int[] TouchBoardWhere(double TouchX , double TouchY){//将触摸坐标位置转换为棋盘区域位置
        for(int i = 0 ; i < board_width ; i++){
            for(int j = 0 ; j < board_length ; j++){
                if(TouchX > first_boardLocationX + j * BoardWidthForOne
                        && TouchX < first_boardLocationX + (j+1)*BoardWidthForOne
                        && TouchY > first_boardLocationY + i * BoardWidthForOne
                        && TouchY < first_boardLocationY + (i+1) * BoardWidthForOne){
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }
}
